package com.cross.test;

import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.dom4j.DocumentException;

import com.cross.test.util.DataBaseHelper;

public class DBCPTestCase extends Thread {

	private String sql;
	private String poolname;
	private Connection c;
	private final static String table = "cross_test";
	
	private static int num = 0;
	
	public int getNum(){
		synchronized(this){
			return num++;
		}
	}

	public DBCPTestCase(String poolname, Connection c, String sql)
			throws SQLException {
		this.poolname = poolname;
		this.c = c;
		this.sql = sql;

		destory();
		init();
		loadData();
	}

	public static void main(String[] args) throws FileNotFoundException,
			DocumentException, SQLException {
		
		com.mysql.jdbc.Driver d;

		for (int i = 0; i < 3; i++) {
			final String sql = "select * from " + table;

		//   new DBCPTestCase("one", DataBaseHelper.getDbConnection("one"), sql).start();
			 new DBCPTestCase("two", DataBaseHelper.getDbConnection("two"),sql).start();
		}

	}

	public void init() throws SQLException {
		String sql = "create table " + table
				+ " (id char(36),name varchar(100))";
		Statement s = c.createStatement();
		s.execute(sql);
		s.close();
		
		String keywords = c.getMetaData().getSQLKeywords();
		System.out.println(keywords);
		String escapse = c.getMetaData().getSearchStringEscape();
		System.out.println(escapse);
		
	}

	public void loadData() throws SQLException {
		String sql = "insert into " + table + " (id,name) values (?,?)";
		PreparedStatement pst = c.prepareStatement(sql);
		int n= 0;
		for (int i = 0; i < 10; i++) {
			n = getNum();
			pst.setString(1, "id:" + n);
			pst.setString(2, "name:" + n);
			pst.execute();
		}
		pst.close();
	}

	public void destory() {
		String sql = "drop table " + table;
		try {
			Statement s = c.createStatement();
			s.execute(sql);
			s.close();
		} catch (SQLException e) {
		}
	}

	public void run() {
		try {
			ResultSet rs = c.createStatement().executeQuery(sql);
			while (rs.next()) {
				System.out.println(rs.getString(1));
			}
			if (poolname.equals("one"))
				System.out.println("one:\n"
						+ DataBaseHelper.GetPoolStats("one"));
			else
				System.out.println("two:\n" + DataBaseHelper.GetPoolStats("two"));
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataBaseHelper.close(c);
		}
	}

}
